const storagePrefix = 'collect-'
class Result {
  constructor(message, data = {}) {
    this.message = message
    this.data = data
  }
}

const getStorageItemById = id => {
  const res = uni.getStorageInfoSync();
  const filterList = res.keys.filter(key => key === `${storagePrefix}${id}`);
  return filterList[0] ? uni.getStorageSync(filterList[0]) : null
}

const api = {
  add: (data) => {
    if (!data.id) {
      console.error('收藏add接口参数缺失地点的id')
      return;
    }
    return new Promise((resolve) => {
      uni.setStorageSync(`${storagePrefix}${data.id}`, data);
      resolve(new Result('收藏成功'))
    })
  },
  delete: id => {
    return new Promise((resolve) => {
      uni.removeStorageSync(`${storagePrefix}${id}`)
      resolve(new Result('取消成功'))
    })
  },
  detail: id => {
    return new Promise((resolve) => {
      const item = getStorageItemById(id);
      resolve(new Result('查询成功', item))
    })
  },
  getCount: () => {
    return new Promise((resolve) => {
      const res = uni.getStorageInfoSync();
      const filterList = res.keys.filter(key => key.indexOf(storagePrefix) !== -1);
      resolve(new Result('查询成功', { list: filterList, totalCount: filterList.length }))
    })
  },
}

export default api
